<template>
  <view class="chat-test-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-left" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <view class="navbar-title">聊天功能测试</view>
      <view class="navbar-right"></view>
    </view>

    <!-- 测试内容区域 -->
    <view class="test-content">
      <!-- 用户登录测试 -->
      <view class="test-section">
        <view class="section-title">用户登录测试</view>
        <view class="test-item">
          <input 
            class="test-input" 
            v-model="testUserId" 
            placeholder="输入用户ID进行测试登录"
          />
          <button class="test-btn" @click="testLogin" :disabled="!testUserId.trim()">
            {{ isLoggedIn ? '已登录' : '模拟登录' }}
          </button>
        </view>
        <view class="status-text" :class="{ success: isLoggedIn }">
          状态: {{ isLoggedIn ? '已登录' : '未登录' }}
        </view>
      </view>

      <!-- MQTT连接测试 -->
      <view class="test-section">
        <view class="section-title">WebSocket连接测试</view>
        <view class="test-item">
          <button class="test-btn" @click="testConnection" :disabled="isConnecting">
            {{ isConnected ? '断开连接 ' : (isConnecting ? '连接中...' :  '连接WebSocket') }}
          </button>
        </view>
        <view class="status-text" :class="{ success: isConnected, error: connectionError }">
          连接状态: {{ connectionStatus }}
        </view>
      </view>

      <!-- 消息发送测试 -->
      <view class="test-section">
        <view class="section-title">消息发送测试</view>
        <view class="test-item">
          <input 
            class="test-input" 
            v-model="targetUserId" 
            placeholder="目标用户ID"
          />
        </view>
        <view class="test-item">
          <input 
            class="test-input" 
            v-model="testMessage" 
            placeholder="测试消息内容"
          />
          <button 
            class="test-btn" 
            @click="sendTestMessage" 
            :disabled="!canSendMessage"
          >
            发送消息
          </button>
        </view>
      </view>

      <!-- 页面跳转测试 -->
      <view class="test-section">
        <view class="section-title">页面跳转测试</view>
        <view class="test-item">
          <button class="test-btn" @click="goToChatPage">
            跳转到聊天页面
          </button>
        </view>
      </view>

      <!-- 测试日志 -->
      <view class="test-section">
        <view class="section-title">测试日志</view>
        <scroll-view class="log-container" scroll-y="true">
          <view class="log-item" v-for="(log, index) in testLogs" :key="index">
            <text class="log-time">{{ log.time }}</text>
            <text class="log-content" :class="log.type">{{ log.content }}</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import chatManager from '../../utils/chat.js'
import { getUserInfo, setUserInfo } from '../../utils/auth.js'

export default {
  data() {
    return {
      testUserId: 'test_user_001',
      targetUserId: 'test_user_002',
      testMessage: '这是一条测试消息',
      isLoggedIn: false,
      isConnected: false,
      isConnecting: false,
      connectionError: false,
      connectionStatus: '未连接',
      testLogs: [],
      messageHandlerId: null
    }
  },

  computed: {
    canSendMessage() {
      return this.isConnected && 
             this.isLoggedIn && 
             this.targetUserId.trim() && 
             this.testMessage.trim()
    }
  },

  onLoad() {
    this.addLog('页面加载完成', 'info')
    
    // 检查是否已有用户信息
    const userInfo = getUserInfo()
    if (userInfo) {
      this.testUserId = userInfo.userId
      this.isLoggedIn = true
      this.addLog(`检测到已登录用户: ${userInfo.userId}`, 'success')
    }

    // 检查连接状态
    if (chatManager.getConnectionStatus()) {
      this.isConnected = true
      this.connectionStatus = '已连接'
      this.addLog('检测到WebSocket已连接', 'success')
    }
  },

  onUnload() {
    // 移除消息监听
    if (this.messageHandlerId) {
      chatManager.offMessage(this.messageHandlerId)
    }
  },

  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 测试登录
    async testLogin() {
      if (this.isLoggedIn) {
        // 退出登录
        this.isLoggedIn = false
        uni.removeStorageSync('userInfo')
        this.addLog('用户已退出登录', 'info')
        return
      }

      try {
        this.addLog(`尝试登录用户: ${this.testUserId}`, 'info')
        
        // 模拟用户信息
        const userInfo = {
          userId: this.testUserId,
          username: this.testUserId,
          token: 'test_token_' + Date.now()
        }
        
        setUserInfo(userInfo)
        this.isLoggedIn = true
        this.addLog('登录成功', 'success')

        // 如果WebSocket已连接，进行登录
        if (this.isConnected) {
          chatManager.login(this.testUserId)
          this.addLog('WebSocket登录请求已发送', 'info')
        }

      } catch (error) {
        this.addLog(`登录失败: ${error.message}`, 'error')
      }
    },

    // 测试连接
    async testConnection() {
      if (this.isConnected) {
        // 断开连接
        chatManager.disconnect()
        this.isConnected = false
        this.connectionStatus = '已断开'
        this.connectionError = false
        this.addLog('WebSocket连接已断开', 'info')
        return
      }

      try {
        this.isConnecting = true
        this.connectionStatus = '连接中...'
        this.connectionError = false
        this.addLog('开始连接WebSocket...', 'info')

        await chatManager.connect()
        
        this.isConnected = true
        this.connectionStatus = '已连接'
        this.addLog('WebSocket连接成功', 'success')

        // 注册消息监听
        this.messageHandlerId = chatManager.onMessage((message) => {
          this.addLog(`收到消息: ${JSON.stringify(message)}`, 'success')
        })

        // 如果已登录，自动进行WebSocket登录
        if (this.isLoggedIn) {
          chatManager.login(this.testUserId)
          this.addLog('自动发送登录请求', 'info')
        }

      } catch (error) {
        this.connectionError = true
        this.connectionStatus = '连接失败'
        this.addLog(`连接失败: ${error.message}`, 'error')
      } finally {
        this.isConnecting = false
      }
    },

    // 发送测试消息
    sendTestMessage() {
      try {
        this.addLog(`发送消息给 ${this.targetUserId}: ${this.testMessage}`, 'info')
        
        const message = chatManager.sendMessage(this.targetUserId, this.testMessage)
        this.addLog(`消息已发送: ${message.messageId}`, 'success')
        
        // 清空输入框
        this.testMessage = ''

      } catch (error) {
        this.addLog(`发送消息失败: ${error.message}`, 'error')
      }
    },

    // 跳转到聊天页面
    goToChatPage() {
      if (!this.targetUserId.trim()) {
        this.addLog('请先输入目标用户ID', 'error')
        return
      }

      const url = `/pages/chat/chat?targetUserId=${this.targetUserId}&title=测试聊天`
      this.addLog(`跳转到聊天页面: ${url}`, 'info')
      
      uni.navigateTo({
        url: url,
        success: () => {
          this.addLog('页面跳转成功', 'success')
        },
        fail: (error) => {
          this.addLog(`页面跳转失败: ${JSON.stringify(error)}`, 'error')
        }
      })
    },

    // 添加日志
    addLog(content, type = 'info') {
      const log = {
        time: new Date().toLocaleTimeString(),
        content: content,
        type: type
      }
      this.testLogs.unshift(log)
      
      // 限制日志数量
      if (this.testLogs.length > 50) {
        this.testLogs = this.testLogs.slice(0, 50)
      }
      
      console.log(`[${type.toUpperCase()}] ${content}`)
    }
  }
}
</script>

<style scoped>
.chat-test-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 自定义导航栏 */
.custom-navbar {
  height: 88rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #e5e5e5;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.navbar-left, .navbar-right {
  width: 120rpx;
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 48rpx;
  color: #333333;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
}

/* 测试内容区域 */
.test-content {
  flex: 1;
  padding: 120rpx 32rpx 32rpx;
  overflow-y: auto;
}

.test-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 24rpx;
  border-bottom: 2rpx solid #007aff;
  padding-bottom: 16rpx;
}

.test-item {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.test-input {
  flex: 1;
  height: 80rpx;
  padding: 0 24rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.test-input:focus {
  border-color: #007aff;
}

.test-btn {
  height: 80rpx;
  padding: 0 32rpx;
  background-color: #007aff;
  color: #ffffff;
  border: none;
  border-radius: 12rpx;
  font-size: 28rpx;
  min-width: 160rpx;
}

.test-btn:disabled {
  background-color: #cccccc;
  color: #999999;
}

.status-text {
  font-size: 28rpx;
  color: #666666;
  padding: 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.status-text.success {
  color: #28a745;
  background-color: #d4edda;
}

.status-text.error {
  color: #dc3545;
  background-color: #f8d7da;
}

/* 日志容器 */
.log-container {
  height: 400rpx;
  background-color: #f8f9fa;
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  padding: 16rpx;
}

.log-item {
  display: flex;
  margin-bottom: 16rpx;
  font-size: 24rpx;
}

.log-time {
  color: #999999;
  margin-right: 16rpx;
  min-width: 120rpx;
}

.log-content {
  flex: 1;
  word-wrap: break-word;
}

.log-content.info {
  color: #333333;
}

.log-content.success {
  color: #28a745;
}

.log-content.error {
  color: #dc3545;
}
</style>